package com.zf.zfed.audit

import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.MediaController
import android.widget.VideoView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.io.FileOutputStream

class VideoPlayerActivity : AppCompatActivity() {
    
    private lateinit var videoView: VideoView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置全屏播放
        videoView = VideoView(this)
        setContentView(videoView)
        
        // 获取传递的视频路径
        val videoPath = intent.getStringExtra("video_path") ?: "file:///android_asset/操作视频.mp4"
        Log.d("VideoPlayerActivity", "Video path: $videoPath")
        
        // 设置媒体控制器
        val mediaController = MediaController(this)
        videoView.setMediaController(mediaController)
        mediaController.setAnchorView(videoView)
        
        // 设置视频准备好的监听器
        videoView.setOnPreparedListener { 
            Log.d("VideoPlayerActivity", "Video prepared, starting playback")
            mediaController.show(0)
            videoView.start()
        }
        
        // 设置错误监听器
        videoView.setOnErrorListener { mediaPlayer, what, extra ->
            Log.e("VideoPlayerActivity", "Video error: what=$what, extra=$extra")
            Toast.makeText(this, "视频播放出错: what=$what, extra=$extra", Toast.LENGTH_LONG).show()
            finish()
            true
        }
        
        // 设置完成监听器
        videoView.setOnCompletionListener {
            Log.d("VideoPlayerActivity", "Video playback completed")
            Toast.makeText(this, "视频播放完成", Toast.LENGTH_SHORT).show()
        }
        
        try {
            // 对于assets中的文件，我们需要特殊处理
            if (videoPath.startsWith("file:///android_asset/")) {
                playVideoFromAssets(videoPath)
            } else {
                // 检查URI是否有效
                val uri = Uri.parse(videoPath)
                if (uri != null) {
                    Log.d("VideoPlayerActivity", "Playing video from URI: $uri")
                    videoView.setVideoURI(uri)
                    videoView.requestFocus()
                } else {
                    throw IllegalArgumentException("Invalid URI: $videoPath")
                }
            }
        } catch (e: Exception) {
            Log.e("VideoPlayerActivity", "Exception while setting video URI", e)
            Toast.makeText(this, "无法播放此视频: ${e.message}", Toast.LENGTH_LONG).show()
            finish()
        }
    }
    
    private fun playVideoFromAssets(assetPath: String) {
        try {
            val fileName = assetPath.substringAfter("file:///android_asset/")
            Log.d("VideoPlayerActivity", "Playing video from assets: $fileName")
            
            // 检查assets中是否存在该文件
            val assetList = assets.list("")
            if (assetList?.contains(fileName) != true) {
                throw IllegalArgumentException("Asset file not found: $fileName")
            }
            
            // 将assets中的文件复制到缓存目录
            val cachedFile = File(cacheDir, fileName)
            assets.open(fileName).use { input ->
                FileOutputStream(cachedFile).use { output ->
                    input.copyTo(output)
                }
            }
            
            // 使用缓存文件的URI播放视频
            val uri = Uri.fromFile(cachedFile)
            Log.d("VideoPlayerActivity", "Cached file URI: $uri")
            videoView.setVideoURI(uri)
            videoView.requestFocus()
        } catch (e: Exception) {
            Log.e("VideoPlayerActivity", "Exception while playing video from assets", e)
            Toast.makeText(this, "无法播放此视频: ${e.message}", Toast.LENGTH_LONG).show()
            finish()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        if (::videoView.isInitialized) {
            videoView.stopPlayback()
        }
        
        // 清理缓存文件
        try {
            val cachedFile = File(cacheDir, "操作视频.mp4")
            if (cachedFile.exists()) {
                cachedFile.delete()
            }
        } catch (e: Exception) {
            Log.w("VideoPlayerActivity", "Failed to delete cached video file", e)
        }
    }
}